<template>
  <div class="content_modal">
    <MainLayout>
      <template #header>
        <div class="flex_block header_modal">
          <div class="title">测试用例</div>
          <div class="flex_block right_model">
            <el-button type="success" icon="Eleme" @click="handlePartRun"
              >执行部分</el-button
            >
            <el-button type="success" icon="Eleme" @click="handleAllRun"
              >执行全部</el-button
            >
          </div>
        </div>
      </template>
      <template #main>
        <div class="flex_block main_modal">
          <div class="left_block" v-loading="menu_loading">
            <LeftMeun
              :list="menu_list"
              :active="menu_active"
              @change="handleMenuActive"
            ></LeftMeun>
          </div>
          <div class="right_block">
            <SearchLayout>
              <!-- 搜索模块 -->
              <template #search>
                <el-input
                  v-model="search_params.queryParams.name"
                  placeholder="请输入用例名称"
                  clearable
                  class="search_item"
                />
                <el-select
                  v-model="search_params.queryParams.severity"
                  placeholder="请选择优先级"
                  class="search_item"
                  clearable
                >
                  <el-option
                    class="select_item"
                    v-for="item in priority_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-button type="primary" @click="getCaseList('saerch')"
                  >搜索</el-button
                >
                <el-button @click="handleSearchReset">重置</el-button>
                <el-button type="success" @click="handleActiveTableCase"
                  >执行选中用例</el-button
                >
              </template>
              <!-- table -->
              <template #table>
                <el-table
                  :data="table_list"
                  border
                  v-loading="table_loading"
                  @selection-change="handleSelectionChange"
                  :style="{ height: 'calc(100vh - 260px)' }"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column
                    prop="name"
                    label="名称"
                    min-width="180"
                    align="center"
                  />
                  <el-table-column
                    prop="title"
                    label="测试场景"
                    min-width="100"
                    align="center"
                  />
                  <el-table-column
                    prop="severity"
                    label="优先级"
                    min-width="80"
                    align="center"
                  />
                  <el-table-column
                    label="操作"
                    width="100"
                    fixed="right"
                    align="center"
                  >
                    <template #default="{ row }">
                      <div class="flex_block_around operate_block">
                        <div
                          class="color_primary cursor_pointer"
                          @click="handleDetails(row)"
                        >
                          查看
                        </div>
                        <div
                          class="color_success cursor_pointer"
                          @click="handleExecute(row)"
                        >
                          执行
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <Pagination
                  :page="search_params.pageNum"
                  :size="search_params.pageSize"
                  :total="table_total"
                  @change="handlePaginationChange"
                ></Pagination>
              </template>
            </SearchLayout>
          </div>
        </div>
      </template>
    </MainLayout>
  </div>

  <!-- 单个 执行的模态框 -->
  <el-dialog
    v-model="isShowExecute"
    :title="`发起测试 (${execute_case.name})`"
    width="500"
    :before-close="handleExecuteClose"
    :close-on-click-modal="false"
  >
    <div class="dialog_main_block">
      <div class="main_block_item flex_block">
        <div class="item_title must">测试时间：</div>
        <el-date-picker
          v-model="execute_params.case_time"
          type="datetime"
          placeholder="不填默认立即执行"
          :clearable="false"
          :show-now="false"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </div>
      <div class="main_block_item flex_block">
        <div class="item_title must">执行环境：</div>
        <el-select
          v-model="execute_params.execute_environment"
          placeholder="执行环境"
        >
          <el-option
            class="select_item"
            v-for="item in environmentList"
            :key="item.envName"
            :label="item.envName"
            :value="item.envName"
          />
        </el-select>
      </div>
      <div class="main_block_item flex_block">
        <div class="item_title must">测试文件：</div>
        <el-select
          v-model="execute_params.execute_path"
          placeholder="请选择测试文件"
        >
          <el-option
            class="select_item"
            v-for="item in execute_case.dataList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleExecuteClose">取消</el-button>
        <el-button
          type="primary"
          :loading="but_loading"
          @click="handleExecuteConfirm"
        >
          执行
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 发起测试模态框 -->
  <InitiateCaseModal
    :isShowDialog="isShowCaseDialog"
    @confirm="handelCaseConfirm"
    @close="handelCaseClose"
    :list="InitiateCaseData"
    :showDelete="showDeleteCaseDialog"
    :showPriority="showPriorityCaseDialog"
  ></InitiateCaseModal>
  <!-- 选择用例部分 模态框 -->
  <SelectCaseModal
    :case_tree="case_tree"
    :isShowDialog="isShowSelectCaseDialog"
    @close="handelSelectCaseClose"
    @confirm="handelSelectCaseConfirm"
  ></SelectCaseModal>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import {
  CaseMenuList,
  AdminCaseDataList,
  AdminExampleExecuteTestExampleBatch,
  ObtainAllCaseTree,
} from "@/api/test_case";
import { AdminEnvironmentList } from "@/api/settings.js";

import SelectCaseModal from "./components/SelectCaseModal.vue";
import LeftMeun from "./components/LeftMeun.vue";
import { formatTime } from "@/utils/index.js";
import { ElMessage } from "element-plus";

const router = useRouter();

const menu_loading = ref(false);
const menu_list = ref([]);
const menu_active = ref(null); //选中的id
const search_params = reactive({
  //列表的搜索条件
  pageNum: 1,
  pageSize: 10,
  queryParams: {
    name: "",
    severity: "",
    path: "",
  },
});
const table_loading = ref(true);
const table_list = ref([]); //用例列表数据
const table_total = ref(0);
const but_loading = ref(false); //按钮的锁定
const priority_options = ref([]); //优先级
const multipleSelection = ref([]); //存放table选中的数据
const isShowCaseDialog = ref(false); //是否显示 发起测试 的 模态框
const InitiateCaseData = ref([]); //发起测试的 列表数据
const allCaseData = ref([]);
const showDeleteCaseDialog = ref(true); //是否显示 删除 的 功能
const showPriorityCaseDialog = ref(false); //是否显示 优先级 的 功能
const case_tree = ref([]); //用例树
const environmentList = ref([]);

onMounted(() => {
  getMenuData(); //获取左侧菜单数据
  getEnvironmentData(); //获取执行环境数据
  getCaseTreeData(); //获取用例树
});

// 获取左侧菜单数据
const getMenuData = () => {
  menu_loading.value = true;
  CaseMenuList()
    .then((res) => {
      console.log("sasasas", res);
      menu_list.value = addIsShow(res || []);
      if (menu_list.value.length !== 0) {
        menu_active.value = menu_list.value[0].name;
        search_params.queryParams.path = menu_active.value;
        getCaseList();
      }
    })
    .finally(() => {
      menu_loading.value = false;
      table_loading.value = false;
    });
};
// 左侧菜单添加isShow字段
const addIsShow = (data) => {
  // 确保data是数组
  return (data || []).map((item) => {
    // 创建新对象，避免直接修改原数据
    const newItem = { ...item, isShow: true };

    // 递归处理子节点
    if (newItem.children) {
      newItem.children = addIsShow(newItem.children);
    }

    return newItem;
  });
};
//获取执行环境数据
const getEnvironmentData = () => {
  let obj = {
    pageNum: 1,
    pageSize: 2000,
    queryParams: {},
  };
  AdminEnvironmentList(obj).then((res) => {
    environmentList.value = res.list || [];
  });
};
// 处理 菜单 选中
const handleMenuActive = (event, list) => {
  menu_active.value = event.name;
  console.log("menu_active", menu_active);
  console.log("list", list);
  let path = handleActiveData(menu_list.value, menu_active.value);
  search_params.queryParams.path = path;
  getCaseList();
};
const handleActiveData = (menuList, targetName, currentPath = "") => {
  for (const item of menuList) {
    // 构建当前项的完整路径
    const path = currentPath ? `${currentPath}/${item.name}` : item.name;

    // 如果找到目标项，返回完整路径
    if (item.name === targetName) {
      return path;
    }

    // 如果有子菜单，递归查找
    if (item.children && item.children.length > 0) {
      const result = handleActiveData(item.children, targetName, path);
      if (result) return result; // 找到结果直接返回
    }
  }

  // 未找到匹配项
  return null;
};
// 获取菜单模块的列表数据
const getCaseList = (type) => {
  table_loading.value = true;
  if (type === "search") {
    search_params.pageNum = 1;
  }
  AdminCaseDataList(search_params)
    .then((res) => {
      console.log("列表数据", res);
      table_list.value = res.list || [];
      table_total.value = res.total;
      // 提取 severity 并去重，同时转换为 { value, label } 格式
      // 处理逻辑：过滤null → 提取唯一值 → 转换格式
      priority_options.value = [
        ...new Set(
          table_list.value
            .map((item) => item.severity)
            .filter((severity) => severity != null && severity != "") // 过滤null和undefined
        ),
      ].map((severity) => ({
        value: severity,
        label: severity, // 标签映射，默认转为字符串
      }));
    })
    .finally(() => {
      table_loading.value = false;
    });
};
// 重置 -- 搜索
const handleSearchReset = () => {
  search_params.queryParams.name = "";
  search_params.queryParams.severity = "";
  getCaseList("search");
};
const handlePaginationChange = (value) => {
  search_params.pageNum = value.page;
  search_params.pageSize = value.size;
  getCaseList();
};
// 处理选中的用例 --- table自带
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleActiveTableCase = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要执行的用例");
  } else {
    InitiateCaseData.value = [];
    isShowCaseDialog.value = true;
    InitiateCaseData.value = multipleSelection.value;
  }
};
// 发起测试 模态框 的执行 按钮
const handelCaseConfirm = (list, params) => {
  console.log("测试的数据", list, params);
  let exampleList = [];
  list.forEach((item) => {
    exampleList.push({
      id: item.id,
      title: item.title,
      story: item.story,
      name: item.name,
      scene: item.scene,
      severity: item.severity,
      description: item.description,
      step: item.step,
      code: item.code,
      data: item.dataList.find((val) => val.id == item.isDefaultId),
    });
  });
  let obj = {
    executeTime: params.time,
    concNum: params.concurrency + "",
    envName: params.environment,
    exampleList: exampleList,
  };
  // console.log("发起测试的参数", obj);

  handleFinalExecution(obj);
};
// 发起测试 模态框 的取消 按钮
const handelCaseClose = () => {
  isShowCaseDialog.value = false;
  showDeleteCaseDialog.value = true;
  showPriorityCaseDialog.value = false;
};
// 单个执行 （table右侧）-----------------------------
const execute_case = ref({}); //当前 单个执行 的用例数据
const isShowExecute = ref(false); //单个执行 的模态框
const execute_params = reactive({
  case_time: '', //默认当前时间
  execute_environment: null, // 执行环境
  execute_path: null, // 测试文件
});

// 单个执行 的点击按钮（table右侧）
const handleExecute = (item) => {
  console.log("点击了执行按钮", item);
  execute_case.value = item; //存一份数据
  execute_params.case_time = '';
  if (environmentList.value.length > 0) {
    const isDefault = environmentList.value.find((val) => val.default);
    if (isDefault) {
      execute_params.execute_environment = isDefault.envName;
    } else {
      execute_params.execute_environment = environmentList.value[0].envName;
    }
  }
  if (execute_case.value.dataList && execute_case.value.dataList.length > 0) {
    const file = execute_case.value.dataList.find(
      (value) => value.isDefault == 1
    );
    execute_params.execute_path = file?.id || null;
  }
  isShowExecute.value = true;
};
// 模态框取消
const handleExecuteClose = () => {
  isShowExecute.value = false;
};
// 模态框确定
const handleExecuteConfirm = () => {
  // if (!execute_params.case_time) return ElMessage.warning("请选择执行时间");
  // if (execute_params.case_time) {
  //   // 匹配最后一个 ":数字" 并替换为 ":00"
  //   execute_params.case_time = execute_params.case_time.replace(
  //     /:\d{2}$/,
  //     ":00"
  //   );
  // }
  // if (execute_params.time < formatTime()) {
  //   return ElMessage.warning("执行时间不能早于当前时间");
  // }
  if (!execute_params.execute_environment)
    return ElMessage.warning("请选择要执行的环境");
  if (!execute_params.execute_path)
    return ElMessage.warning("请选择要执行的测试文件");
  console.log("点击单个执行", execute_case.value, execute_params);
  let dataList = JSON.parse(JSON.stringify(execute_case.value.dataList || []));
  let obj = {
    executeTime: execute_params.case_time,
    concNum: "1",
    envName: execute_params.execute_environment,
    exampleList: [
      {
        id: execute_case.value.id,
        title: execute_case.value.title,
        story: execute_case.value.story,
        name: execute_case.value.name,
        scene: execute_case.value.scene,
        severity: execute_case.value.severity,
        description: execute_case.value.description,
        step: execute_case.value.step,
        code: execute_case.value.code,
        data: dataList.find((item) => item.id == execute_params.execute_path),
      },
    ],
  };
  handleFinalExecution(obj);
};
const handleFinalExecution = (obj) => {
  but_loading.value = true;
  AdminExampleExecuteTestExampleBatch(obj)
    .then((res) => {
      ElMessage.success(
        "测试任务已启动，可到【测试记录】中查看本次测试状态和测试结果"
      );
      handleExecuteClose();
    })
    .finally((res) => {
      but_loading.value = false;
    });
};
// -----------------------------------------------
// 跳转 到 详情
const handleDetails = (row) => {
  router.push({
    path: "/TestCase/detail",
    query: { id: row.id },
  });
};
const isShowSelectCaseDialog = ref(false); //是否显示 选择用例 模态框
// 部分执行
const handlePartRun = () => {
  console.log("部分执行");
  isShowSelectCaseDialog.value = true;
};
// 关闭 部分执行模态框
const handelSelectCaseClose = () => {
  isShowSelectCaseDialog.value = false;
};
//  确定 部分执行模态框
const handelSelectCaseConfirm = (list) => {
  console.log("list", list);
  InitiateCaseData.value = [];
  isShowCaseDialog.value = true;
  InitiateCaseData.value = list;
};
const handleAllRun = () => {
  if (table_loading.value)
    return ElMessage.warning("用例还在获取中，请稍等...");
  console.log("全部执行");
  showDeleteCaseDialog.value = false; //不需要显示删除功能
  showPriorityCaseDialog.value = true;
  InitiateCaseData.value = [];
  isShowCaseDialog.value = true;
  InitiateCaseData.value = allCaseData.value;
};
//获取用例树数据
const getCaseTreeData = () => {
  allCaseData.value = [];
  ObtainAllCaseTree()
    .then((res) => {
      console.log("用例树数据", res);

      let list = JSON.parse(JSON.stringify(res || []));
      let treeData = [];
      Object.keys(list).forEach((level1) => {
        const level1Content = list[level1];
        let level1_obj = {
          name: level1,
          checked: true,
          is_arrow: true,
          children: [],
        };
        Object.keys(level1Content).forEach((level2) => {
          const level2Content = level1Content[level2];
          allCaseData.value = [...allCaseData.value, ...level2Content];
          let level2_obj = {
            name: level2,
            checked: true,
            is_arrow: true,
            children: level2Content || [],
          };
          level1_obj.children.push(level2_obj);
        });
        treeData.push(level1_obj);
      });
      case_tree.value = treeData;
      console.log("获取用例数据", case_tree.value);
      console.log("全部用例树", allCaseData.value);
    })
    .finally(() => {});
};
</script>
<style scoped lang="scss">
.header_modal {
  width: 100%;
  align-items: center;
  justify-content: space-between;
  .title {
    margin-top: -6px;
    font-weight: 700;
    letter-spacing: 2px;
    font-size: 18px;
  }
  .right_model {
    margin-top: -6px;
  }
}
.main_modal {
  height: calc(100vh - 125px);
  border-radius: 8px;
  .left_block {
    width: 200px;
    min-width: 200px;
    height: 100%;
    background-color: #fff;
    .left_item {
      height: 38px;
      width: 100%;
      font-size: 14px;
      color: #666;
      display: flex;
      align-items: center;
      padding-left: 20px;
      .el-icon {
        margin: 0 5px;
      }
      img {
        width: 16px;
        height: 16px;
        margin: 0 5px;
      }
      cursor: pointer;
      &:hover {
        background-color: #cccccc;
      }
      &.active {
        background-color: #e8f3ff;
      }
    }
  }
  .right_block {
    width: 100%;
    flex: 1;
    background-color: #fff;
    margin-left: 5px;
    padding: 10px 15px;
    .search_item {
      width: 200px;
      margin-right: 8px;
    }
  }
}
// 单个执行 的 发起测试 模态框样式
.dialog_main_block {
  .main_block_item {
    align-items: center;
    margin-bottom: 15px;
    .item_title {
      min-width: 100px;
      text-align: center;
    }
  }
}
</style>
